package com.gzm.framework.handler;


import com.gzm.framework.common.CommonResult;
import com.gzm.framework.common.ResultCode;
import com.gzm.framework.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Objects;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public CommonResult<String> baseException(BaseException e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(e.getMessage());
    }

    /**
     * 路径不存在
     *
     * @param e NoHandlerFoundException
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public CommonResult<String> handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(ResultCode.VALIDATE_FAILED);
    }


    /**
     * Exception 异常捕获
     *
     * @param e Exception
     * @return json
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.failed(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<String> validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return CommonResult.failed(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return CommonResult.failed(message);
    }


}
